package cn.edu.njtc.util;

import java.sql.*;
import java.util.ResourceBundle;

public class DBUtil {
    //定义成员字段
    private Connection connection;
    private PreparedStatement preparedStatement;
    private ResultSet resultSet;
    //把驱动声明为变量
    private ResourceBundle bundle;

    // 准备驱动和连接的准备工作（优先级最高）
    {
        //引入驱动 com.mysql.cj.jdbc.Driver
        // 读取配置文件中的驱动字符串
        //Properties 和 Bundle
        bundle = ResourceBundle.getBundle("db");
        //读取配置的操作

        try {
            Class.forName(bundle.getString("driver"));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 构建连接
     */
    private Connection createConnection() throws SQLException {
        String url = bundle.getString("url");
        String username = bundle.getString("username");
        String password = bundle.getString("password");

        //设计单例的连接对象：当connection为空或者关闭时，才实例化
        //否则，无需重复创建，直接返回即可
        if (connection == null || connection.isClosed()) {
            connection = DriverManager.getConnection(url, username, password);
        }
        return connection;
    }

    /**
     * 执行增删改的方法
     *
     * @param updateSql,params 增删改类型的sql语句,占位的参数
     * @return 影响行数
     */
    public int executeUpdate(String updateSql, Object... params) throws SQLException {
        //通过调用createConnection方法“产生”连接对象
        preparedStatement = createConnection().prepareStatement(updateSql);

        //传参
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }

        //执行
        return preparedStatement.executeUpdate();
    }

    public ResultSet executeQuery(String querySql, Object... params) throws SQLException {
        preparedStatement = createConnection().prepareStatement(querySql);
        for (int i = 0; i < params.length; i++) {
            preparedStatement.setObject(i + 1, params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    public void closeResultSet() throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
    }

    public void closePreparedStatement() throws SQLException {
        if (preparedStatement != null) {
            preparedStatement.close();
        }
    }

    public void closeConnection() throws SQLException {
        if (connection != null) {
            connection.close();
        }
    }

    public void close() throws SQLException {
        closeResultSet();
        closePreparedStatement();
        closeConnection();
    }
}
